package cn.sofwin.blog.web;

import cn.sofwin.blog.entity.Article;
import cn.sofwin.blog.entity.User;
import cn.sofwin.blog.service.ArticleService;
import cn.sofwin.blog.service.impl.ArticleServiceImpl;
import cn.sofwin.blog.utils.HttpHelper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文章表单处理
 * @author ZX
 * @version 1.0
 */
@WebServlet("/blog/article/form")
public class ArticleFormServlet extends HttpServlet {

    /** 文章服务接口 */
    private ArticleService articleService = ArticleServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 如果ID参数不为空，则代表要 修改指定的文章
        String id = req.getParameter("id");
        if(StringUtils.isNoneBlank(id)){
            // 从数据库中查询文章信息
            Article article = articleService.get(Integer.valueOf(id));
            System.out.println(article);
            // 添加到请求作用域
            req.setAttribute("a", article);
        }

        // 转发到文章表单页面
        req.getRequestDispatcher("/articleForm.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpHelper.charset(req);

        String id = req.getParameter("id");
        String title = req.getParameter("title");
        String summary = req.getParameter("summary");
        String content = req.getParameter("content");

        // 获取当前登录的用户
        User user = (User) req.getSession().getAttribute("LOGIN_USER");

        if(StringUtils.isBlank(id)){
            // 发表文章
            articleService.publish(user, title, summary, content);
        }else {
            // 修改文章
            articleService.edit(user, id, title, summary, content);
        }

        // 重定向到首页
        resp.sendRedirect("/index");
    }
}